package com.csw.shuanfa.CodeImprove.poi;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

@Slf4j
public class PoiUtil {

    /**
     * @param patriarch XSSFDrawing
     * @param workbook  表信息
     * @param initRow   当前行信息
     * @param startRow  图片起始行
     * @param endRow    结束行
     */
    private static void setImg(XSSFDrawing patriarch, XSSFWorkbook workbook, String filePath, int initRow, short startRow, short endRow) throws IOException {

        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

        String png = imageToBase64(filePath);
        if (!ObjectUtils.isEmpty(png)) {
            BufferedImage bufferImg = toImage(png);

            try {
                ImageIO.write(bufferImg, "png", byteArrayOut);
            } catch (IOException e) {
                //图片状态失败：" + e);
            }

            //XSSFSheet sheet1 = wb.getSheet("Sheet1");
            //anchor主要用于设置图片的属性
            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255, startRow, initRow, endRow, initRow + 1);
            //0跟随单元格保持一致，单元格改变，图片跟着改变
            //1、2基本一致，图片始终定位在初始化导出后的单元格左上角，且大小不变
            //3图片漂浮与单元格之上，不参与单元格的变化，始终保持不变
            anchor.setAnchorType(ClientAnchor.AnchorType.byId(0));
            //插入图片
            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
        }
    }

    private static BufferedImage toImage(String png) throws IOException {
        return toImage(StringUtils.isEmpty(png) ? null : String.valueOf(new BASE64Decoder().decodeBuffer(png)));
    }

    /**
     * 通过图片的url获取图片的base64字符串,同时压缩图片
     *
     * @param imgUrl 图片url
     * @return 返回图片base64的字符串
     */
    public static String imageToBase64(String imgUrl) {
        if (ObjectUtils.isEmpty(imgUrl) || "null".equals(imgUrl)) {
            return null;
        }
        URL url;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return Base64.getEncoder().encodeToString(outStream.toByteArray());
        } catch (Exception e) {
            log.error("图片解析失败 {}. /n msg:{} ", imgUrl, e);
            return null;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (outStream != null) {
                    outStream.close();
                }
                if (httpUrl != null) {
                    httpUrl.disconnect();
                }
            } catch (IOException e) {
                log.error("图片解析失败:{} ", e);
            }
        }
    }
}
